#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' main entry '
__author__ = 'pingwu you'


from asyncio.events import set_event_loop
import aiomysql
async def create_pool(loop=None, **kw):    
    global __pool
    __pool = await aiomysql.create_pool(
        host=kw.get('host', kw['host']),
        port=kw.get('port', 3306),
        user="kw['user']",
        password=kw['password'],
        db=kw['database'],
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),
        loop=loop
    )

#SQL语句的占位符是?，而MySQL的占位符是%s，select()函数在内部自动替换
async def select(sql, args, size=None):    
    global __pool
    with (await __pool) as conn:
        cur = await conn.cursor(aiomysql.DictCursor)
        await cur.execute(sql.replace('?', '%s'), args or ())
        if size:
            rs = await cur.fetchmany(size)
        else:
            rs = await cur.fetchall()
        await cur.close()        
        return rs


async def execute(sql, args):
    with (await __pool) as conn:
        try:
            cur = await conn.cursor()
            await cur.execute(sql.replace('?', '%s'), args)
            affected = cur.rowcount
            await cur.close()
        except BaseException as e:
            raise
        return affected


async def entry_handle():  
    print("--------aiomysql 11111111111111---------------")  
    await create_pool(host='192.168.0.35', user='root', password='770619', database='python_test')    
    print("--------aiomysql 22222222222222---------------") 
    rs = await select("select * from student where id= %s","2")
    print("--------aiomysql 33333333333333---------------") 
    print(rs)
    rs = await execute("update student set name=%s where id= %s",("异步出来的啊1111111111","2"))
    print("--------aiomysql 444444444444444---------------") 
    print(rs)
    rs = await select("select * from student where id= %s","2")
    print("--------aiomysql 555555555555555---------------") 
    print(rs)

def start_handle():  
    import asyncio
    loop = asyncio.new_event_loop()
    set_event_loop(loop)
    result = loop.run_until_complete(entry_handle())
    #loop.close()